library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;
 -- Alu with : add, sub , and , or instructions
entity alu is
   port
   (
        i1 : in std_logic_vector(31 downto 0);
	i2 : in std_logic_vector(31 downto 0);
	ctrl : in std_logic_vector(3 downto 0);
	ris : out std_logic_vector (31 downto 0);
	z: out std_logic;
	c: out std_logic

      
   );
end entity alu;
 
architecture Behavioral of alu is
 
   signal Temp: std_logic_vector(32 downto 0);
 
begin
 
   process(i1, i2, ctrl, temp) is
   begin
      z <= '0';
      case ctrl is
 	 when "0010" => -- res = nib1 + nib2, flag = carry = overflow
 	    Temp   <= std_logic_vector((unsigned("0" & i1) + unsigned(i2)));
		if(temp="00000000000000000000000000000000") then z<='1'; end if;
            ris <= temp(31 downto 0);
 	    c   <= temp(32);
 	 when "0110" => -- res = |nib1 - nib2|, flag = 1 iff nib2 > nib1
 	    if (i1 >= i2) then
 	       
		temp <= std_logic_vector(unsigned("0" & i1) - unsigned(i2));
		ris<=temp(31 downto 0);
 	       c   <= '0';
		if(temp="00000000000000000000000000000000") then z<='1'; end if;
            else
 	       temp <= std_logic_vector(unsigned("0" & i2) - unsigned(i1));
		ris<=temp(31 downto 0);
		if(temp="00000000000000000000000000000000") then z<='1'; end if;
 	       c   <= '1';
            end if;
 	 when "0000" =>
 	         temp <= i1 and i2;
		if(temp="00000000000000000000000000000000") then z<='1'; end if;
	         ris<=temp(31 downto 0) ;
 	 when "0001" =>

 	    temp <= i1 or i2;if(temp="00000000000000000000000000000000") then z<='1'; end if;ris<=temp(31 downto 0);
 	 
 	 when others => -- res = nib1 + nib2 + 1, flag = 0
 	    Temp   <= std_logic_vector((unsigned("0" & i1) + unsigned(not i2)) + 1);
		if(temp="00000000000000000000000000000000") then z<='1'; end if;
 	    ris <= temp(31 downto 0);
 	    c   <= temp(32);
      end case;
   end process;
 
end architecture Behavioral;
